import Vue from "vue";
import {
  getPlaylistDetail,
  getSongUrl,
  getLyricApi,
  searchApi,
  getToplistsApi,
  getDefaultSearchKeywordApi,
  getArtistHotSongsApi,
  getPersonalizedPlaylist,
  getPersonalizedNewSong,
} from "@/api/music";
import { parseLyric } from "@/utils/lrc-parser";

// 一些精选歌单ID
const playlistIds = [
  3778678, // 云音乐飙升榜
  2884035, // 云音乐新歌榜
];

const musicModule = {
  namespaced: true,
  state: {
    playlist: [],
    currentSongIndex: 0,
    isPlaying: false,
    showMusicDetail: false,
    currentTime: 0,
    duration: 0,
    isPlayerCollapsed: true,
    lyric: null,
    parsedLyric: [],
    currentLyricLine: 0,
    isSearching: false,
    searchResults: [],
    toplists: [],
    defaultSearchKeyword: "",
    hotPlaylists: [],
    newSongs: [],
  },
  mutations: {
    SET_PLAYLIST(state, playlist) {
      state.playlist = playlist;
    },
    SET_CURRENT_SONG_INDEX(state, index) {
      state.currentSongIndex = index;
    },
    SET_IS_PLAYING(state, status) {
      state.isPlaying = status;
    },
    SET_SHOW_MUSIC_DETAIL(state, status) {
      state.showMusicDetail = status;
    },
    SET_SONG_URL(state, { index, url }) {
      if (state.playlist[index]) {
        Vue.set(state.playlist[index], "url", url);
      }
    },
    SET_CURRENT_TIME(state, time) {
      state.currentTime = time;
    },
    SET_DURATION(state, duration) {
      state.duration = duration;
    },
    TOGGLE_PLAYER_COLLAPSE(state) {
      state.isPlayerCollapsed = !state.isPlayerCollapsed;
    },
    SET_LYRIC(state, lyricData) {
      state.lyric = lyricData;
      state.parsedLyric = parseLyric(lyricData?.lrc?.lyric);
    },
    SET_CURRENT_LYRIC_LINE(state, index) {
      state.currentLyricLine = index;
    },
    SET_IS_SEARCHING(state, status) {
      state.isSearching = status;
    },
    SET_SEARCH_RESULTS(state, results) {
      state.searchResults = results;
    },
    ADD_SONG_TO_PLAYLIST(state, song) {
      const existingIndex = state.playlist.findIndex((s) => s.id === song.id);
      if (existingIndex === -1) {
        state.playlist.unshift(song);
        state.currentSongIndex = 0;
      } else {
        state.currentSongIndex = existingIndex;
      }
    },
    SET_TOPLISTS(state, toplists) {
      state.toplists = toplists;
    },
    SET_DEFAULT_SEARCH_KEYWORD(state, keyword) {
      state.defaultSearchKeyword = keyword;
    },
    SET_HOT_PLAYLISTS(state, playlists) {
      state.hotPlaylists = playlists;
    },
    SET_NEW_SONGS(state, songs) {
      state.newSongs = songs;
    },
  },
  actions: {
    async loadInitialData({ dispatch }) {
      // 直接加载飙升榜作为初始歌单
      await dispatch("loadPlaylist", 3778678);
      // 同时获取所有榜单列表用于排行榜tab
      await dispatch("fetchToplists");
      await dispatch("fetchDefaultSearchKeyword");
      await dispatch("fetchHotPlaylists");
      await dispatch("fetchNewSongs");
    },
    async fetchToplists({ commit, state }) {
      if (state.toplists.length > 0) return;
      try {
        const res = await getToplistsApi();
        commit("SET_TOPLISTS", res.data.list);
      } catch (error) {
        console.error("获取排行榜失败:", error);
      }
    },
    async fetchDefaultSearchKeyword({ commit }) {
      try {
        const res = await getDefaultSearchKeywordApi();
        commit("SET_DEFAULT_SEARCH_KEYWORD", res.data.data.showKeyword);
      } catch (error) {
        console.error("获取默认搜索词失败:", error);
      }
    },
    async fetchHotPlaylists({ commit }) {
      try {
        const res = await getPersonalizedPlaylist(30);
        if (res.data.result) {
          const playlists = res.data.result.map((item) => ({
            id: item.id,
            name: item.name,
            coverImgUrl: item.picUrl,
            playCount: item.playCount,
          }));
          commit("SET_HOT_PLAYLISTS", playlists);
        }
      } catch (error) {
        console.error("获取热门歌单失败:", error);
      }
    },
    async fetchNewSongs({ commit }) {
      try {
        const res = await getPersonalizedNewSong(20); // 获取20首推荐新歌
        if (res.data.result) {
          const songs = res.data.result.map((item) => ({
            id: item.id,
            name: item.name,
            artists: item.song.artists.map((a) => ({ id: a.id, name: a.name })),
            artist: item.song.artists.map((a) => a.name).join("/"),
            album: item.song.album.name,
            cover: item.song.album.picUrl,
            duration: item.song.duration / 1000,
            url: "",
          }));
          commit("SET_NEW_SONGS", songs);
        }
      } catch (error) {
        console.error("获取推荐新歌失败:", error);
      }
    },
    async loadPlaylist({ commit, dispatch }, playlistId) {
      try {
        const res = await getPlaylistDetail(playlistId);
        const tracks = res.data.playlist.tracks.map((song) => ({
          id: song.id,
          name: song.name,
          artists: song.ar.map((a) => ({ id: a.id, name: a.name })),
          artist: song.ar.map((a) => a.name).join("/"),
          album: song.al.name,
          cover: song.al.picUrl,
          url: "",
        }));
        commit("SET_PLAYLIST", tracks);
        if (tracks.length > 0) {
          commit("SET_CURRENT_SONG_INDEX", 0); // 默认从第一首开始
          await dispatch("loadSongUrl", { index: 0 });
          await dispatch("fetchLyric", tracks[0].id);
        }
      } catch (error) {
        console.error("加载歌单失败:", error);
      }
    },
    async loadArtistTopSongs({ commit, dispatch }, artistId) {
      try {
        const res = await getArtistHotSongsApi(artistId);
        const tracks = res.data.songs.map((song) => ({
          id: song.id,
          name: song.name,
          artists: song.ar.map((a) => ({ id: a.id, name: a.name })),
          artist: song.ar.map((a) => a.name).join("/"),
          album: song.al.name,
          cover: song.al.picUrl,
          url: "",
        }));
        commit("SET_PLAYLIST", tracks);
        if (tracks.length > 0) {
          commit("SET_CURRENT_SONG_INDEX", 0);
          await dispatch("loadSongUrl", { index: 0 });
          await dispatch("fetchLyric", tracks[0].id);
          commit("SET_IS_PLAYING", true);
        }
      } catch (error) {
        console.error("加载歌手热门歌曲失败:", error);
      }
    },
    async loadSongUrl({ commit, state }, { index }) {
      const song = state.playlist[index];
      if (song && !song.url) {
        try {
          const res = await getSongUrl(song.id);
          const songUrl = res.data.data[0].url;
          if (songUrl) {
            commit("SET_SONG_URL", { index, url: songUrl });
          } else {
            commit("SET_SONG_URL", { index, url: null });
            console.warn(`歌曲 ${song.name} 没有可用的播放源。`);
          }
        } catch (error) {
          console.error("获取歌曲URL失败:", error);
          commit("SET_SONG_URL", { index, url: null });
        }
      }
    },
    async fetchLyric({ commit }, songId) {
      try {
        const res = await getLyricApi(songId);
        commit("SET_LYRIC", res.data);
      } catch (error) {
        console.error("获取歌词失败:", error);
        commit("SET_LYRIC", null);
      }
    },
    play({ commit, state }) {
      if (state.playlist[state.currentSongIndex].url) {
        commit("SET_IS_PLAYING", true);
      }
    },
    pause({ commit }) {
      commit("SET_IS_PLAYING", false);
    },
    togglePlay({ commit, state, dispatch }) {
      if (state.playlist.length === 0) return;

      const song = state.playlist[state.currentSongIndex];
      if (!song.url) {
        dispatch("loadSongUrl", { index: state.currentSongIndex }).then(() => {
          if (state.playlist[state.currentSongIndex].url) {
            commit("SET_IS_PLAYING", !state.isPlaying);
          }
        });
      } else {
        commit("SET_IS_PLAYING", !state.isPlaying);
      }
    },
    async changeSong({ dispatch, commit, state }, index) {
      if (index < 0 || index >= state.playlist.length) return;
      commit("SET_CURRENT_SONG_INDEX", index);
      commit("SET_IS_PLAYING", false);
      await dispatch("loadSongUrl", { index });
      await dispatch("fetchLyric", state.playlist[index].id);

      if (state.playlist[index].url) {
        commit("SET_IS_PLAYING", true);
      }
    },
    nextSong({ dispatch, state }) {
      if (state.playlist.length <= 1) return;
      let newIndex = state.currentSongIndex + 1;
      if (newIndex >= state.playlist.length) {
        newIndex = 0;
      }
      dispatch("changeSong", newIndex);
    },
    prevSong({ dispatch, state }) {
      if (state.playlist.length <= 1) return;
      let newIndex = state.currentSongIndex - 1;
      if (newIndex < 0) {
        newIndex = state.playlist.length - 1;
      }
      dispatch("changeSong", newIndex);
    },
    openMusicDetail({ commit }) {
      commit("SET_SHOW_MUSIC_DETAIL", true);
    },
    closeMusicDetail({ commit }) {
      commit("SET_SHOW_MUSIC_DETAIL", false);
    },
    togglePlayerCollapse({ commit }) {
      commit("TOGGLE_PLAYER_COLLAPSE");
    },
    updateCurrentTime({ commit, state }, time) {
      commit("SET_CURRENT_TIME", time);
      if (state.parsedLyric && state.parsedLyric.length > 0) {
        let i = state.parsedLyric.findIndex((line) => line.time > time);
        if (i === -1) {
          // 如果没找到，说明是最后一句或者已经结束
          commit("SET_CURRENT_LYRIC_LINE", state.parsedLyric.length - 1);
        } else {
          commit("SET_CURRENT_LYRIC_LINE", i - 1);
        }
      }
    },
    async search({ commit }, keywords) {
      if (!keywords) {
        commit("SET_SEARCH_RESULTS", []);
        return;
      }
      commit("SET_IS_SEARCHING", true);
      try {
        const res = await searchApi({ keywords, type: 1 });
        const songs = res.data.result.songs.map((song) => ({
          id: song.id,
          name: song.name,
          artist: song.ar.map((a) => a.name).join("/"),
          album: song.al.name,
          cover: song.al.picUrl,
          duration: song.dt / 1000,
          url: "",
        }));
        commit("SET_SEARCH_RESULTS", songs);
      } catch (error) {
        console.error("搜索失败:", error);
        commit("SET_SEARCH_RESULTS", []);
      } finally {
        commit("SET_IS_SEARCHING", false);
      }
    },
    async playSearchResult({ commit, dispatch, state }, song) {
      const songInPlaylist = state.playlist.find((s) => s.id === song.id);

      commit("ADD_SONG_TO_PLAYLIST", song);

      if (!songInPlaylist || !songInPlaylist.url) {
        const index = state.playlist.findIndex((s) => s.id === song.id);
        await dispatch("loadSongUrl", { index });
        await dispatch("fetchLyric", song.id);
      }

      commit("SET_IS_PLAYING", true);
    },
  },
  getters: {
    currentSong: (state) => {
      return state.playlist[state.currentSongIndex] || {};
    },
    currentSongUrl: (state) => {
      const song = state.playlist[state.currentSongIndex];
      return song ? song.url : "";
    },
  },
};

export default musicModule;
